<template>
    <div class="user-list">
        <Layout>
            <Header class="header">
                <Row>
                    <Col :span="24">
                    <div>
                        <span class="border-left"></span>
                        用户列表
                    </div>
                    </Col>
                </Row>
            </Header>
            <Content class="content">
                <div class="search-box">
                    <Row :gutter="16" style="min-width: 1024px">
                        <Col :span="6">
                            用户账号：
                            <Input v-model="searchForm.account" placeholder="用户ID/账号" style="width:auto" />
                        </Col>
                        <Col :span="6">
                            用户昵称：
                            <Input v-model="searchForm.name" placeholder="用户昵称" style="width:auto" />
                        </Col>
                        <Col :span="6">
                            注册时间：
                            <DatePicker v-model="create_time" :options="options" :start-date="new Date(new Date() - (30*24*60*60*1000))"
                                type="daterange" placement="bottom" :value="'yyyy-MM-dd'" placeholder="请选择时间" style="width: auto"
                                @on-change="returnDate">
                            </DatePicker>
                        </Col>
                        <Col :span="6">
                            <div class="search-btn" @click="getTableData(1)">查询</div>
                        </Col>
                    </Row>
                </div>

                <div class="table-box">
                    <el-table ref="table" :data="tableData" size="mini" style="width: 100%;min-width: 800px">
                        <!-- <el-table-column type="selection" width="55">
						</el-table-column> -->
                        <el-table-column align="center" prop="account" label="用户账号"></el-table-column>
                        <el-table-column align="center" label="用户昵称">
                            <template slot-scope="scope">
                                <p>{{scope.row.name ? scope.row.name : '（暂无）'}}</p>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column align="center" label="用户职业">
                            <template slot-scope="scope">
                                <p>{{scope.row.major ? scope.row.major : '（暂无）'}}</p>
                            </template>
                        </el-table-column> -->
                        <el-table-column
                            align="center"
                            prop="rec_code"
                            label="推荐码">
                        </el-table-column>
                        <el-table-column align="center" prop="create_time" label="注册时间">
                        </el-table-column>
                        <el-table-column align="center" label="最近登录">
                            <template slot-scope="scope">
                                <p>{{scope.row.login_time}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="可用余额">
                            <template slot-scope="scope">
                                <p>￥{{scope.row.balance}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="200" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="look(scope.row)">查看详情</el-button>
                                <el-button type="text" size="small" @click="roleConfig(scope.row.id,scope.row.role_id,scope.row.territory,scope.row.rate)">角色设定</el-button>
                                <el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <el-dialog title="角色设定" :visible.sync="dialogFormVisible" class="dialog_box" :before-close="handleCancel">
                    <!-- <CheckboxGroup v-model="selectedRoles" @on-change="roleChange" :max="3">
                        <Checkbox v-for="(item,index) in roles" :key="index" :label="item.name"></Checkbox>
                    </CheckboxGroup> -->
                    <p style="margin-left:10px">提示：最多只能选择四个角色，不选择默认为基础角色</p>
                    <el-checkbox-group size="mini" v-model="selectedRoles" :max="4" @change="roleChange">
                        <el-checkbox border v-for="(item,index) in roles" :key="index" :label="item.id" :disabled="isDisable(item.id,item.name)">{{item.name}}</el-checkbox>
                    </el-checkbox-group>

                    <Divider v-show="isAreaShow || isTownShow || isProviceShow" />
                    <!-- <div>
						<label>代理地区（区县）：</label>
						
					</div> -->
                    <div class="role_edit_box">
                        <div class="ivu-form" style="margin-top:20px;width:100%">
                            <div class="ivu-form-item-required ivu-form-item fead hidden" :class="isAreaShow ? 'show' : ''">
                                <label class="ivu-form-item-label" style="width: 120px;">代理区域(区县)</label>
                                <div class="ivu-form-item-content" style="margin-left: 120px;">
                                    <Cascader class="u_input" v-for="(item,i) in formData.area" :key="i" :data="area" :load-data="loadAreaData" filterable v-model="formData.area[i]"></Cascader>
                                    <div class="addArea addBtn" @click="addArea">+</div>
                                </div>
                            </div>
                            <div class="ivu-form-item-required ivu-form-item fead hidden" :class="isTownShow ? 'show' : ''">
                                <label class="ivu-form-item-label" style="width: 120px;">代理区域(市级)</label>
                                <div class="ivu-form-item-content u_content">
                                    <Cascader class="u_input" v-for="(item,i) in formData.town" :key="i" :data="town" :load-data="loadTownData" filterable v-model="formData.town[i]"></Cascader>
                                    <div class="addTown addBtn" @click="addTown">+</div>
                                </div>
                            </div>
                            <div class="ivu-form-item-required ivu-form-item fead hidden" :class="isProviceShow ? 'show' : ''">
                                <label class="ivu-form-item-label" style="width: 120px;">代理区域(省级)</label>
                                <div class="ivu-form-item-content" style="margin-left: 120px;">
                                    <Cascader class="u_input" v-for="(item,i) in formData.province" :key="i" :data="province" filterable v-model="formData.province[i]"></Cascader>
                                    <div class="addTown addBtn" @click="addProvince">+</div>
                                </div>
                            </div>
                            <div class="ivu-form-item-required ivu-form-item fead hidden" :class="isRateShow ? 'show' : ''">
                                <label class="ivu-form-item-label" style="width: 120px;">合伙人提成</label>
                                <div class="ivu-form-item-content" style="margin-left: 120px;">
                                    <Input v-model="formData.rate" style="width:200px">
                                    <span slot="append">%</span>
                                    </Input>
                                </div>
                            </div>
                        </div>
                        <!-- <Form style="margin-top:20px;width:50%">
                            <FormItem label="服务提成（区县）" class="hidden fead ivu-form-item-required" :class="isAreaShow ? 'show' : ''">
                                <Input v-model="formData.rate" style="width:200px">
                                    <span slot="append">%</span>
                                </Input>
                            </FormItem>
                            <FormItem label="服务提成（市级）" class="hidden fead ivu-form-item-required" :class="isTownShow ? 'show' : ''">
                                <Input v-model="formData.rate" style="width:200px">
                                    <span slot="append">%</span>
                                </Input>
                            </FormItem>
                            <FormItem label="服务提成（省级）" class="hidden fead ivu-form-item-required" :class="isProviceShow ? 'show' : ''">
                                <Input v-model="formData.rate" style="width:200px">
                                    <span slot="append">%</span>
                                </Input>
                            </FormItem>
                        </Form> -->
                    </div>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="handleCancel">取 消</el-button>
                        <el-button type="primary" @click="handleSubmit">确 定</el-button>
                    </div>
                </el-dialog>

                <div class="page-box">
                    <Page :total="total" :page-size="pageSize" show-elevator show-total @on-change="pageChange" />
                </div>
            </Content>
            <Footer>
                <p class="copy-right">Copyright © {{host}}, All Rights Reserved.</p>
            </Footer>
        </Layout>
    </div>
</template>

<script>
    import * as api from '@/api/api'
    export default {
        data() {
            return {
                host: window.location.host,
                loading: this.$store.state,
                searchForm: {
                    account: '',
                    name: ''
                },
                create_time_search: '',
                create_time: ['', ''],
                options: {
                    disabledDate(date) {
                        return date && date.valueOf() > Date.now();
                    }
                }, //日期选择范围配置
                tableData: [], //表格数据
                dialogFormVisible: false,
                roles: [],
                selectedRoles: [],
                province: [], //省
                town: [], //市
                area: [], //区县
                formData: {
                    area: [],
                    town: [],
                    province: [],
                    rate: ''
                },
                editUserId: null,
                isAreaShow: false,
                isTownShow: false,
                isProviceShow: false,
                isRateShow: false,
                total: 0, //数据总条数
                pageSize: 10, //每页显示条数
                current_page: 1, //当前页码
            }
        },
        mounted() {
            this.getTableData(0);
        },

        computed: {

        },

        watch: {

        },

        methods: {
            pageChange(current_page) {
                this.current_page = current_page;
                this.getTableData(3);
            },

            getTableData(index) {
                if (index === 1 || index === 0) {
                    this.current_page = 1;
                };
                let body = {
                    model: 'Users',
                    with: {},
                    offset: this.current_page - 1,
                    limit: this.pageSize,
                    orderBy: 'create_time desc',
                    condition: {
                        is_delete: 0
                    },
                    search: this.searchForm
                }
                if (this.create_time_search) {
                    body.condition.create_time = this.create_time_search
                }
                if(this.searchForm.account) {
                    body.condition.account = this.searchForm.account;
                }
                this.loading.isLoading = true;
                api.getDataList(body).then(res => {
                    if (res.data.code === 200) {
                        let data = res.data.data
                        this.total = data.count * 1;
                        this.tableData = data.data;
                        this.getRoles();
                    } else {
                        this.$Notice.error({
                            title: '错误',
                            desc: res.data.msg
                        });
                    }
                }).catch(err => {
                    this.loading.isLoading = false;
                    this.$Notice.error({
                        title: '错误',
                        desc: '服务器错误,请联系管理员（' + err + '）',
                    });
                });
            },
            returnDate(date) {
                if (date[0] == '') {
                    this.create_time_search = '';
                    return false;
                }
                let newTime = '';
                for (let index = 0; index < date.length; index++) {
                    let one = date[index];
                    let time1 = one.split(' ')[0];
                    if (index === 1) {
                        newTime = newTime + '&' + time1 + ',between';
                    } else {
                        newTime = newTime + time1;
                    }
                }
                this.create_time_search = newTime;
            },
            look(row) {
                this.$router.push({
                    name: 'UserDetails',
                    params: {
                        userId: row.id,
                        balance: row.balance
                    }
                })
            },
            getRoles() {
                let body = {
                    model: 'Roles',
                    with: {
                        0: 'roleUsers'
                    },
                    contUser: '',
                    offset: 0,
                    limit: 10000,
                    orderBy: '',
                    condition: {
                        is_start: '1',
                        is_delete: '0'
                    }
                };
                api.getDataList(body).then(res => {
                    if (res.data.code === 200) {
                        this.roles = res.data.data.data;
                        this.getProvince();
                    }
                })
            },
            roleConfig(userId, role_id, territory, rate) {
                this.editUserId = userId;
                this.isAreaShow = this.isTownShow = this.isProviceShow = false;
                this.selectedRoles = [];
                let roleArr = role_id.split(',');
                for (const item of roleArr) {
                    for (const i of this.roles) {
                        if (item == i.id) {
                            this.selectedRoles.push(i.id)
                        }
                    }
                }
                this.roleChange(this.selectedRoles);
                if (rate) {
                    this.formData.rate = rate;
                }
                if (territory) {
                    let arr1 = territory.split('&');
                    let reset = (arr) => {
                        if (arr.length > 0) {
                            if (arr.length === 1) {
                                this.formData.province.push(arr);
                            } else if (arr.length === 2) {
                                this.formData.town.push(arr) ;
                            } else {
                                this.formData.area.push(arr);
                            }
                        }
                    }
                    for (const item of arr1) {
                        let one = item.split(',');
                        reset(one);
                    }
                } else {
                    this.formData = {
                        area: [],
                        town: [],
                        province: []
                    }
                }
                this.dialogFormVisible = true;
            },
            roleChange(roles) {
                let reg1 = /3/;
                let reg2 = /4/;
                let reg3 = /5/;
                let reg4 = /2/;
                let str = roles.join(',');
                if (reg1.test(str)) {
                    this.isProviceShow = true;
                } else {
                    this.isProviceShow = false;
                    this.formData.province = [];
                }
                if (reg2.test(str)) {
                    this.isTownShow = true;
                } else {
                    this.isTownShow = false;
                    this.formData.town = [];
                }
                if (reg3.test(str)) {
                    this.isAreaShow = true;
                } else {
                    this.isAreaShow = false;
                    this.formData.area = [];
                }
                if (reg4.test(str)) {
                    this.isRateShow = true;
                } else {
                    this.isRateShow = false;
                    this.formData.rate = '';
                }
            },
            isDisable(id, name) {
                // let flag = false;
                // if(name == '区县代理' || name == '市级代理' || name == '省级代理') {
                //     for (const item of this.selectedRoles) {
                //         if(item == '区县代理' || item == '市级代理' || item == '省级代理') {
                //             if(item != name){
                //                 flag = true
                //             }
                //             break;
                //         }
                //     }
                // }
                // return flag;
                return false;
            },
            handleSubmit() {
                let body = {
                    model: 'Users',
                    data: {},
                    update_condition: {
                        id: this.editUserId
                    }
                };
                let roles = this.selectedRoles.join(',');
                let territory = '';
                if (this.formData.area.length > 0) {
                    let area = this.formData.area.join(',');
                    territory = territory + area;
                };
                if (this.formData.town.length > 0) {
                    let town = this.formData.town.join(',')
                    if (territory) {
                        territory = territory + '&' + town;
                    } else {
                        territory = territory + town;
                    }
                }
                if (this.formData.province.length > 0) {
                    let province = this.formData.province.join(',')
                    if (territory) {
                        territory = territory + '&' + province;
                    } else {
                        territory = territory + province;
                    }
                };
                if (this.formData.rate) {
                    body.data.rate = this.formData.rate;
                };
                if (territory) {
                    body.data.territory = territory;
                };
                body.data.role_id = roles;
                // console.log(body);
                // return false;
                this.loading.isLoading = true;
                this.dialogFormVisible = false;
                api.createData(body).then(res => {
                    this.loading.isLoading = false;
                    if (res.data.code === 200) {
                        this.$Message.success('设置成功');
                        this.getTableData();
                    }
                })
            },
            handleCancel() {
                this.dialogFormVisible = false;
                this.formData = {
                    area: [],
                    town: [],
                    province: [],
                    rate: ''
                }
            },
            del(id) {
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let body = {
                        model: "Users",
                        data: {
                            is_delete: 1
                        },
                        update_condition: {
                            id: id
                        }
                    };
                    this.loading.isLoading = true;
                    api.createData(body).then(res => {
                        if (res.data.code === 200) {
                            this.getTableData();
                            this.$Message.success('删除成功');
                        } else {
                            this.loading.isLoading = false;
                            this.$Notice.error({
                                title: '错误',
                                desc: res.data.msg
                            });
                        }
                    }).catch(err => {
                        this.loading.isLoading = false;
                        this.$Notice.error({
                            title: '错误',
                            desc: '服务器错误,请联系管理员（' + err + '）',
                        });
                    });
                })
            },
            //省市区
            getProvince() {
                let body = {
                    model: 'Provinces',
                    limit: 1000,
                    offset: 0,
                    orderBy: 'id asc'
                };
                //省
                api.getDataList(body).then(res => {
                    this.loading.isLoading = false;
                    let data = res.data.data.data;
                    // if(roleState === '3') {
                    for (const item of data) {
                        let one = {
                            value: item.province_name,
                            label: item.province_name,
                            id: item.id,
                            type: 0
                        };
                        this.province.push(one)
                    }
                    // }else {
                    for (const item of data) {
                        let area = {
                            value: item.province_name,
                            label: item.province_name,
                            id: item.id,
                            children: [],
                            loading: false,
                            type: 0
                        };
                        let town = {
                            value: item.province_name,
                            label: item.province_name,
                            id: item.id,
                            children: [],
                            loading: false,
                            type: 0
                        };
                        this.area.push(area);
                        this.town.push(town);
                    }
                    // }
                })
            },

            loadAreaData(item, callback) {
                this.loadData(1, item, callback);
            },

            loadTownData(item, callback) {
                this.loadData(2, item, callback);
            },

            loadData(status, item, callback) {
                item.loading = true;
                if (item.type === 0) {
                    let body = {
                        model: 'Citys',
                        limit: 1000,
                        offset: 0,
                        orderBy: 'id asc',
                        condition: {
                            province_id: item.id
                        }
                    };
                    //市
                    api.getDataList(body).then(res => {
                        let data = res.data.data.data;
                        let city = [];
                        if (status === 2) {
                            for (const citys of data) {
                                let one = {
                                    value: citys.city_name,
                                    label: citys.city_name,
                                    id: citys.id,
                                    type: 1
                                };
                                city.push(one)
                            }
                        } else {
                            for (const citys of data) {
                                let one = {
                                    value: citys.city_name,
                                    label: citys.city_name,
                                    id: citys.id,
                                    children: [],
                                    loading: false,
                                    type: 1
                                };
                                city.push(one)
                            }
                        }
                        item.children = city;
                        item.loading = false;
                        callback();
                    })
                } else if (item.type === 1) {
                    let body = {
                        model: 'Areas',
                        limit: 1000,
                        offset: 0,
                        orderBy: 'id asc',
                        condition: {
                            city_id: item.id
                        }
                    };
                    //区
                    api.getDataList(body).then(res => {
                        let data = res.data.data.data;
                        let area = [];
                        for (const areas of data) {
                            let one = {
                                value: areas.area_name,
                                label: areas.area_name,
                            };
                            area.push(one)
                        }
                        item.children = area;
                        item.loading = false;
                        callback();
                    })
                }

            },
            addArea() {
                this.formData.area.push([]);
            },
            addTown() {
                this.formData.town.push([]);
            },
            addProvince() {
                this.formData.province.push([]);
            }
        }
    }

</script>


<style lang="less">
    @import '../../assets/styles/constant.less';

    .user-list {
        width: 100%;
        height: 100%;
        overflow-x: hidden;
        overflow-y: auto;
        background-color: #f5f7f9;

        .ivu-layout {
            min-height: 100%;
        }

        .header {
            font-size: 14px;
            line-height: 40px;
            height: 40px !important;
            color: #434343;
            padding: 0 50px;
            background-color: @background;
            border-bottom: 1px solid #ddd;

            .border-left {
                border-left: 5px solid @baseColor;
                margin-right: 4px;
            }
        }

        .content {
            width: 100%;
            min-height: 76%;
            padding: 20px 60px;

            .search-box {
                .search-btn {
                    width: 100px;
                    height: 32px;
                    line-height: 32px;
                    text-align: center;
                    background-color: @greenColor;
                    border-radius: 4px;
                    color: #fff;
                    cursor: pointer;
                }
            }

            .table-box {
                margin-top: 20px;
                width: 100%;

                .el-table th {
                    background-color: #eee;
                    color: #333;
                    font-size: 14px;
                }

                .el-button--text {
                    color: @greenColor;
                }
            }

            .dialog_box {
                .role_edit_box {
                    display: flex;
                }

                .fead {
                    transition: all 0.3s;
                }

                .fead.show {
                    height: auto;
                    margin-bottom: 24px;
                    overflow: initial;
                }

                .hidden {
                    height: 0;
                    overflow: hidden;
                    margin-bottom: 0;
                }
                .u_content {
                    margin-left: 120px;
                    display: flex;
                    flex-wrap: wrap;
                }
                .u_input {
                    width:200px;
                    display: inline-block;
                    margin-right: 4px;
                    margin-bottom: 10px;
                }
                .addBtn {
                    display: inline-block;
                    border: 1px dashed #aaa;
                    padding: 0 10px;
                    height: 32px;
                    cursor: pointer;
                }
            }

            .page-box {
                height: 50px;
                line-height: 50px;
                text-align: right;
                background-color: #fff;
                padding: 0 20px;
            }
        }

        .copy-right {
            text-align: center;
            color: #aaa;
            font-size: 12px;
        }
    }

</style>
